package com.lc.afbx.util;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.widget.DatePicker;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.lc.afbx.R;

import java.text.SimpleDateFormat;
import java.util.Calendar;

/**
 * Created by Administrator on 2016/7/16.
 */
public class DateTimePickDialogFreeUtil implements DatePicker.OnDateChangedListener {

    private Context context;

    private DatePicker datePicker;
    private AlertDialog ad;
    private String dateTime;
    private String initDateTime;

    public DateTimePickDialogFreeUtil(Context context) {
        this.context = context;
    }

    public AlertDialog dateTimePicKDialog(final TextView inputDate) {

        Calendar calendar = Calendar.getInstance();

        initDateTime = calendar.get(Calendar.YEAR) + "-" + calendar.get(Calendar.MONTH) + "-" + calendar.get(Calendar.DAY_OF_MONTH);

        LinearLayout dateTimeLayout = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.common_datetime, null);

        datePicker = (DatePicker) dateTimeLayout.findViewById(R.id.datepicker);

        datePicker.init(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), this);

        ad = new AlertDialog.Builder(context)
                .setTitle(initDateTime)
                .setView(dateTimeLayout)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {

                        inputDate.setText(dateTime);

                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
//                        inputDate.setText("");
                    }
                }).show();

        onDateChanged(datePicker, 0, 0, 0);

        return ad;
    }


    @Override
    public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {

        // 获得日历实例
        Calendar calendar = Calendar.getInstance();

        calendar.set(datePicker.getYear(), datePicker.getMonth(), datePicker.getDayOfMonth());

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        dateTime = sdf.format(calendar.getTime());

        ad.setTitle(dateTime);

    }
}
